#include <pthread.h>
#include <vector>
#include <iostream>
#include <unistd.h>
#define NUM 4
int tickets = 1000;
struct ThreadData
{
  ThreadData(const std::string& threadname, pthread_mutex_t* mutex_p)
    :_name(threadname)
     ,_mutex_p(mutex_p)
  {}
  std::string _name;
  pthread_mutex_t* _mutex_p;// 
};
void* getTicket(void* args)
{
  ThreadData* td = static_cast<ThreadData*>(args);
  while(true)
  {
    pthread_mutex_lock(td->_mutex_p);
    if (tickets > 0)
    {
      usleep(1000);
      std::cout << "new Thread " << td->_name << "->" << tickets-- << std::endl;
      pthread_mutex_unlock(td->_mutex_p);

    }
    else
    {
      pthread_mutex_unlock(td->_mutex_p);
      break;
    }
  }
  return nullptr;
}

int main()
{
  pthread_mutex_t lock;
  pthread_mutex_init(&lock, nullptr);
  std::vector<pthread_t> tids(NUM);
  for (int i = 0; i < NUM; ++i)
  {
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "thread %d", i + 1);
    ThreadData* td = new ThreadData(buffer, &lock);
    pthread_create(&tids[i], nullptr, getTicket, (void*)td);
  }
  for (const auto& tid : tids)
  {
    pthread_join(tid, nullptr);
  }
  pthread_mutex_destroy(&lock);
  return 0;
}
